-module(users).
-export([register/3, login/3, logged/0, logout/0]).

register(Nick, Pass, Email) ->
    case db:add(member, {Nick, Pass, Email}) of
	{ok, _} ->
	    ok;
	{error, bad_nick} ->
	    bad_nick;
	{error, Reason} ->
	    Reason;
	_ ->
	    unknown
    end.

login(Nick, Pass, Cookies) ->
    HashedPass = sha2:hexdigest512(Pass),
    
    case db:validate_member(name, {Nick, HashedPass}) of
	{true, Status, ID} ->
	    set_sessions(ID, Nick, HashedPass, Status),
	    case Cookies of
		[[111,110]] -> 
		    set_cookies(ID, Nick, HashedPass, Status);
		_ ->
		    ok
	    end,
	    ok;
	{false, _} ->
	    wrong_info
    end.

logout() ->
    wf:clear_session(),
    wf_platform:set_cookie(id, "", "/", 1),
    wf_platform:set_cookie(nick, "", "/", 1),
    wf_platform:set_cookie(hpass, "", "/", 1),
    wf_platform:set_cookie(status, "", "/", 1).

logged() ->
    case wf:user() of
	undefined ->
	    case wf_platform:get_cookie(nick) of
		undefined ->
		    false;
		_ ->
		    sessionize_cookies(),
		    logged()
	    end;
	Nick ->
	    case db:validate_member(id, {wf:session(id), wf:session(hpass), wf:session(status)}) and db:validate_member(name, {Nick, wf:session(hpass), wf:session(status)}) of
		true ->
		    true;
		_ ->
		    clear_info(),
		    false
	    end
    end.
		    
	    

set_sessions(ID, N, HP, St) ->
    wf:session(id, ID),
    wf:user(N),
    wf:session(hpass, HP),
    wf:session(status, St).

set_cookies(ID, N, HP, St) ->
    wf_platform:set_cookie(id, ID, "/", 43200),
    wf_platform:set_cookie(nick, N, "/", 43200),
    wf_platform:set_cookie(hpass, HP, "/", 43200),
    wf_platform:set_cookie(status, St, "/", 43200).

sessionize_cookies() ->
    set_sessions( wf_platform:get_cookie(id), wf_platform:get_cookie(nick), wf_platform:get_cookie(hpass), wf_platform:get_cookie(status) ).

clear_info() ->
    set_cookies(cleared, cleared, cleared, cleared),
    sessionize_cookies().
